<template>
  <div class="role">
    <header>
      <span>
        <span>角色名称</span>
         <el-select v-model="role" placeholder="请选择" style="width:200px;margin:0 12px">
          <el-option
            v-for="item in roleNameArr"
            :key="item.key"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </span>
      <span>
        <span>角色状态</span>
        <el-select v-model="state" placeholder="请选择" style="width:200px;margin:0 12px">
          <el-option
            v-for="item in options"
            :key="item.key"
            :label="item.value"
            :value="item.key">
          </el-option>
        </el-select>
      </span>
      <p>
        <el-link type="primary" style="margin-left:8px"  @click="roleAdd">添加角色</el-link>
        <el-button type="primary" style="float: right;" icon="el-icon-search" @click="roleSearch(role,state)">搜索</el-button>
      </p>
    </header>
    <!-- 表格 -->
    <el-table
      :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
      :header-cell-style="{background:'#EBEEF5'}"
      style="width: 100%;margin-left:8px">
      <el-table-column prop="roleid" label="角色ID" ></el-table-column>
      <el-table-column prop="role" label="角色名称" ></el-table-column>
      <el-table-column prop="state" label="状态" >
        <template slot-scope="scope">{{scope.row.state === 'ok'?'已启用':'已冻结'}}</template>
      </el-table-column>

      <el-table-column prop="viewpermissions" label="菜单权限" >
        <template slot-scope="scope" >
          <span style='padding:0 8px'>{{scope.row.chinaArr.length}}</span>
          <el-tooltip placement="top" effect="light">
            <div slot="content">        
              <el-tag 
               v-for="(item,index) in scope.row.chinaArr"
              :key="index"
              type="success"
              style="margin:0 8px"
              >{{item}}</el-tag>
            </div>
            <el-button type="text">查看</el-button>
          </el-tooltip>
        </template> 
      </el-table-column>
     
       <el-table-column prop="roperm" label="操作权限" >
        <template slot-scope="scope" >
          <span style='padding:0 8px'>{{scope.row.oprArr.length}}</span>
          <el-tooltip effect="light"  placement="bottom"  >
            <div slot="content">        
              <el-tag 
               v-for="(item,index) in scope.row.oprArr"
              :key="index"
              type="success"
              style="margin:0 8px"
              >{{item}} </el-tag>
            </div>
            <el-button type="text">查看</el-button>
          </el-tooltip>
        </template> 
      </el-table-column>

      <el-table-column prop="createtime" label="创建时间" >
        <template slot-scope="scope">{{$getDate(scope.row.createtime*1)}}</template>
      </el-table-column>
      <el-table-column prop="date" label="操作" >
        <template slot-scope="scope">
        <el-button type="text" @click="roleEdit(scope.row)">编辑</el-button>
        <el-button type="text" size="mini" @click="roleFreeze(scope.row)">{{scope.row.state === 'ok'?'冻结':'启用'}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页  -->
    <div class="pagination">
     <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5,6,8]" 
            :page-size="pagesize"        
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.length">   
    </el-pagination>
    </div> 
    <!-- 分页结束 -->

    <!-- 弹层编辑 -->
    <div>
      <el-dialog title="编辑" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="角色名称" :label-width="formLabelWidth">
            <el-input v-model="role" autocomplete="off" :disabled="true" style="width:215px"></el-input>
          </el-form-item>
          <el-form-item label="菜单权限" :label-width="formLabelWidth">
            <el-cascader
              :options="this.getreme(Object.keys(menulimits).map(item=>menulimits[item]))"
              :props="props"
              collapse-tags
              v-model="selectedKeys"
              @change = 'handleChange'
              clearable
              ></el-cascader>
          </el-form-item>

          <el-form-item label="权限操作" :label-width="formLabelWidth">
              <el-checkbox-group v-model="form.opr">
              <el-checkbox 
               v-for="(item,index) in Object.keys(oprlimits)" :key="index"
                :label="item"     
                v-model="form.opr"
                >{{oprlimits[item].PermissionName}}</el-checkbox>
                 </el-checkbox-group>
          </el-form-item>

          <el-form-item label="状态" :label-width="formLabelWidth">
              <el-radio v-model="form.state" label="ok">启用</el-radio>
              <el-radio v-model="form.state" label="freeze">冻结</el-radio>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button menu="primary" @click="open">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 编辑结束 -->
  </div>
</template>
<script>
export default {
  data(){
    return {
    // 下拉选
    i :"",
    props: { multiple: true },
    state:'',
    role:"",
    roleNameArr:[],
    tableData:[],  
    test:[], 
    dialogFormVisible: false,
     form: {
          state:'',
          opr:[],
        },
    formLabelWidth: '120px',
    oprlimits:{},//操作权限
    menulimits:{},//菜单权限
    options:[{
      key:'ok',
      value:'已启用'
    },{
      key:'freeze',
      value:'已冻结'
    }],//角色请求列表
    pagesize:5,
    currentPage:1, 
    menuArr:[],  //    每页的数据
    selectedKeys:[[2,3]],
    roleid:''
    }
  },
  mounted(){
    this.initData()
  },
  methods:{
   
    open(){
      this.dialogFormVisible = false  ;
      let jin = this.selectedKeys.map(item=>{
        if(item.length<2){
          return item[0]
        }
        return item[1]
      })
      this.$httpAxios(this.$api.ROLE_EDIT({obj:{roleid:this.roleid,role:this.role,viewpermissions:'['+jin+']',roperm:'['+this.form.opr+']'}}),res=>{
        this.$message({message: res.msg,type: 'success'});
        
      })   
      this.initData()
    },
    handleChange(){

		},
    // 搜索
    roleSearch(){
        if(this.role===''&&this.state==="") return  this.$message({message:'搜索内容不能为空',type: 'wraning'})
        this.$httpAxios(this.$api.ROLE_SEARCH({obj:{role:this.role,state:this.state}}),res=>{
        this.$message({message: res.msg,type: 'success'})
        this.tableData = res.data
      })
    },

    // 编辑数据
    roleEdit(item){
      let str=item.viewpermissions.substring(1,item.viewpermissions.length-1).split(',');
      let twoArr = []

      this.getreme(Object.keys(this.menulimits).slice(1,).map(item=>this.menulimits[item])).forEach(item=>{
        if(item.children){
           item.children.forEach(jtem=>twoArr.push([item.key,jtem.key]))
        }else{
           twoArr.push([item.key])
        }
      })

      let bbb =[]
      str.forEach(k=>{
          return  twoArr.forEach(item=>{  
            if(item.length<2){
              if(item[0]==k) return bbb.push(item)
            }
            if(item[1]==k) return bbb.push(item)
            })
          })
            
      this.selectedKeys = bbb 
      this.roleid = item.roleid 
      this.role = item.role 
      this.form.state = item.state
      this.form.opr =item.roperm?item.roperm.substring(1,item.roperm.length-1).split(","):[]
      this.dialogFormVisible = true
    },
    //添加账号
    roleAdd(){
      this.$router.push('/roleadd')
    },

    // 冻结账号
    roleFreeze(roleid){
      if(roleid.roleid===5){
        return this.$message.success('该用户为超级管理员，无法进行冻结'); 
      }
      this.$confirm('您确定要对当前用户账号'+' '+roleid.role+' '+'进行设置吗', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'})
        .then(() => this.$httpAxios(this.$api.ROLE_FREEZE({roleid:roleid.roleid}),res=>{
            // 加入弹层提示
            this.$message.success(res.msg); 
            // 初始化视图
            this.initData()
        }))
        .catch(() => this.$message.info('已取消'))      
    },

    // 获取数据
    initData(){
      this.$httpAxios(this.$api.ROLE_GETLIST(),res=>{
       this.roleNameArr = res.data.roleData.map(item=>(item.role))
        this.tableData = res.data.roleData
        this.oprlimits = res.data.limits
        this.menulimits = res.data.rolelist
        res.data.roleData.map(item=>{
          let chinaArr = []
          let oprArr = []
          item.viewpermissions.substring(1,item.viewpermissions.length-1).split(',').filter(jtem=>{       
            Object.keys(res.data.rolelist).forEach(roleitem=>{
              if(res.data.rolelist[roleitem].key==jtem){
                if(res.data.rolelist[roleitem].menuTitle){
                  chinaArr.push(res.data.rolelist[roleitem].menuTitle)
                }                
              }
            })
          })
          item.roperm&&item.roperm.substring(1,item.roperm.length-1).split(',').filter(jtem=>{          
            Object.keys(res.data.limits).forEach(roleitem=>{
      
              if(roleitem==jtem){
                if(res.data.limits[roleitem].PermissionName){
                  oprArr.push(res.data.limits[roleitem].PermissionName)
                }                
              }
            })
          })
          item.oprArr = oprArr
         item.chinaArr = chinaArr
        })
      })           
    },
    // 分页器
    handleCurrentChange(currentPage) {

      this.currentPage = currentPage;
    },
    // 每张显示的个数
    handleSizeChange(size) {
      this.pagesize = size;
    },
    // 修改数据格式
    getreme(list){
      let i=1
      let s=1
      let data = [];
      list.forEach((item,s)=> {
         let menu
          let subMenu = {
            key: item.key,
            value: item.key,
            label: item.menuName,
            path: item.path,
            index:i+"-"+s
          }
          
          let index = data.findIndex(k => k.smenuTitle===item.menuTitle)
          if(index !== -1) { 
            data[index].children.push(subMenu)
            s++
            return 
          }
          if(item.menuName){
            menu = {
              index: "" + i,
              value:item.key,
              key:item.key,
              smenuTitle:item.menuTitle,
              label:item.menuTitle,
              title:item.menuName===""?item.menuTitle:item.menuTitle,
              path:item.menuName===""?item.path:"",
              icon:item.menuIcon,
              children: [subMenu]
            }
          }
          else{
            menu = {
            index: "" + i,
            smenuTitle:item.menuTitle,
            label:item.menuTitle,
            title:item.menuName===""?item.menuTitle:item.menuTitle,
            path:item.menuName===""?item.path:"",
            icon:item.menuIcon,
            value:item.key,
            key:item.key,
          }}         
          i++
          data.push(menu)
        })  
      return data
    },
  }
  
}
</script>

<style scoped >
header{
  padding: 8px 0px;
}

</style>
